package org.babygo.connect.handler.client.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

import org.babygo.connect.protocol.GetAndSendFileRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientSendFileOutHandler  extends ChannelOutboundHandlerAdapter{
	private Logger log = LoggerFactory.getLogger(ClientSendFileOutHandler.class);

	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		if (msg instanceof GetAndSendFileRequest){
			log.info("最后真的开始发送文件!");
			File file = ((GetAndSendFileRequest) msg).getFile();
			ByteBuf m = Unpooled.buffer(10);
			RandomAccessFile randomAccessFile = null;
			try {
				randomAccessFile = new RandomAccessFile(file,"rw");
				while(randomAccessFile.getFilePointer()<randomAccessFile.length()){
					//					System.out.println(randomAccessFile.getFilePointer() + "---" + randomAccessFile.length());
					byte[] fileData = null;
					int loadLength = (int) (randomAccessFile.length()-randomAccessFile.getFilePointer());
					if (loadLength<1024){
						fileData = new byte[loadLength];
					} else fileData = new byte[1024];
					randomAccessFile.read(fileData);
					m.writeBytes(fileData);
					m.retain();
					ctx.writeAndFlush(m);
					m.clear();
				}
			} catch (Exception e) {
				log.error("发送文件错误!",e);
			} finally{
				try {
					randomAccessFile.close();
					m.release();
				} catch (IOException e) {
					log.error("关闭文件错误!",e);
				}
			}
		} else log.info("未知的命令");
	}
}